package com.ebt.m.widget.indemnify.chart;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.util.Log;

import com.ebt.m.utils.UIHelper;
import com.ebt.m.widget.indemnify.IndemnifyConfig;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.CombinedXYChart.XYCombinedChartDef;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 绘制利益图
 */
public class EbtIndemnifyA extends AbstractDemoChart {
    public int getShapeType() {
        return shapeType;
    }

    public void setShapeType(int shapeType) {
        this.shapeType = shapeType;
    }

    //取值固定，与后台配置一致
    public static final int SHAPE_AREA_DEFAULT = 0, SHAPE_LINE = 1, SHAPE_BAR = 2;
    private int shapeType = SHAPE_AREA_DEFAULT;
    private IndemnifyConfig indemnifyConfig;
    private Context context;

    private GraphicalView myview;//
    private XYMultipleSeriesDataset dataset = null;// 数据
    private XYMultipleSeriesRenderer renderer;// 渲染
    private int[] shapeTypes;// 形状类型
    private ArrayList<String> useShapeTypes = new ArrayList<String>();// 实际使用的形状类型
    private XYSeries[] xyseries;// x、y数据
    private XYSeriesRenderer[] xySeriesRenderer;// 渲染
    private boolean isShow[] = null;// 是否可见
    /**
     * X坐标数目,固定为22个格
     */
    public static int XLabels = 23;
    /**
     * Y坐标数目
     */
    public static final int YLabels = 15;
    /**
     * 坐标间距
     */
    public static final int BarSpacing = 2;

    public EbtIndemnifyA(Context context, IndemnifyConfig indemnifyConfig) {
        this.context = context;
        this.indemnifyConfig = indemnifyConfig;
        init();
    }

    private void init() {
        //初始化面积图是否显示
        isShow = indemnifyConfig.getIsShow();
        List<double[]> xList = new ArrayList<double[]>();
        List<double[]> values = new ArrayList<double[]>();
        for (int i = 0; i < indemnifyConfig.getXyVaules().length; i++) {
            xList.add((double[]) indemnifyConfig.getXyVaules()[i][0]);
            values.add((double[]) indemnifyConfig.getXyVaules()[i][1]);
        }
        dataset = buildDataset(indemnifyConfig.getTitles(), xList, values);

        shapeTypes = indemnifyConfig.getShapeTypes();
        useShapeTypes.clear();
        for (int i = 0; i < shapeTypes.length; i++) {
            if (shapeTypes[i] == SHAPE_LINE) {
                useShapeTypes.add(LineChart.TYPE);
            } else if (shapeTypes[i] == SHAPE_AREA_DEFAULT) {
                useShapeTypes.add(LineChart.TYPE);
            } else if (shapeTypes[i] == SHAPE_BAR) {
                useShapeTypes.add(BarChart.TYPE);
            }
        }

        PointStyle[] pointStyles = indemnifyConfig.getPointStyles();
        renderer = buildRenderer(indemnifyConfig.getColors(), pointStyles);
        double xMin = 0;
        double xMax = XLabels;
        double yMin = 0;
        double yMax = 1200000;
        super.setChartSettings(renderer, "保障收益图形A", indemnifyConfig.getxTitle(), indemnifyConfig.getyTitle(), xMin, xMax, yMin, yMax,
                indemnifyConfig.getAxesColor(),
                indemnifyConfig.getLabelsColor(),
                indemnifyConfig.getMarginsColor());

    }

    @Override
    public String getName() {
        return "保证收益图形A";
    }

    @Override
    public String getDesc() {
        return "该图为保证收益图形A";
    }

    /**
     * 设置XY坐标范围
     */
    public void setXYRange(double[] initialRange, double[] range) {
        renderer.setInitialRange(initialRange);
        renderer.setRange(initialRange);
        renderer.setPanEnabled(true, true);// 设置xy坐标轴方向是否可以平移
        renderer.setPanLimits(range);//设置xy坐标轴平移范围
//		renderer.setZoomLimits(range);
        //设置起止横轴坐标
        renderer.setXAxisMin(indemnifyConfig.getxInitialMinAge());
        renderer.setXAxisMax(indemnifyConfig.getxInitialMaxAge());
        //设置起止Y轴坐标
        renderer.setYAxisMin(range[2]);
        renderer.setYAxisMax(range[3]);
    }

    /**
     * 计算渲染参数
     */
    public void computeRender() {
        setXYRange(indemnifyConfig.getInitialRange(), indemnifyConfig.getRange());
        renderer.setXLabels(indemnifyConfig.getxLabels());
        renderer.setYLabels(EbtIndemnifyA.YLabels);
        renderer.setBarSpacing(indemnifyConfig.getBarSpacing());
        renderer.setxLabelsInterval(indemnifyConfig.getIntervalAge());//设置横轴刻度之间间距
        // 刻度右对齐
        renderer.setXLabelsAlign(Align.RIGHT);
        renderer.setYLabelsAlign(Align.RIGHT);
    }

    /**
     * 设置显示或者隐藏的图形
     *
     * @param show
     * @param index
     */
    public void setVisible(boolean show, int index) {
        if (show) {
            isShow[index] = true;
        } else {
            isShow[index] = false;
        }
    }

    /**
     * 清除所有数据
     */
    private void clearAllData() {
        for (int i = 0; i < isShow.length; i++) {
            dataset.removeSeries(xyseries[i]);
            renderer.removeSeriesRenderer(xySeriesRenderer[i]);
            useShapeTypes.clear();
        }
    }

    /**
     * 添加显示的数据
     */
    private void addShowData() {
        for (int i = 0; i < isShow.length; i++) {
            if (isShow[i]) {
                dataset.addSeries(xyseries[i]);
                renderer.addSeriesRenderer(xySeriesRenderer[i]);
                if (shapeTypes[i] == SHAPE_LINE) {
                    useShapeTypes.add(LineChart.TYPE);
                } else if (shapeTypes[i] == SHAPE_AREA_DEFAULT) {
                    useShapeTypes.add(LineChart.TYPE);
                } else if (shapeTypes[i] == SHAPE_BAR) {
                    useShapeTypes.add(BarChart.TYPE);
                }
            }
        }
    }

    public GraphicalView getView() {
        clearAllData();
        renderer.setXTitle(indemnifyConfig.getxTitle());
        addShowData();
        computeRender();
        switch (shapeType) {
            case SHAPE_LINE:
                myview = ChartFactory.getCubeLineChartView(context, dataset,
                        renderer, 0.0f);
                break;
            case SHAPE_BAR:
                renderer.setXLabels(0);//不显示横轴刻度
//                renderer.setYLabels(10);
//                renderer.setYAxisMin(0);
//                renderer.setYAxisMax(100);
//                renderer.setBarWidth(23);
//                renderer.setBarSpacing(20);
                renderer.setBarWidth(63);
                myview = ChartFactory.getBarChartView(context, dataset, renderer,
                        BarChart.Type.DEFAULT);
                break;
            default:
                XYCombinedChartDef[] types = new XYCombinedChartDef[useShapeTypes.size()];
                for (int i = 0; i < types.length; i++) {
//				types[i] = useShapeTypes.get(i);//1.2.0
                    types[i] = new XYCombinedChartDef(useShapeTypes.get(i), i);//1.1.0
                }
                myview = ChartFactory.getCombinedXYChartView(context, dataset, renderer, types);
                break;
        }
        return myview;
    }

    @Override
    public XYMultipleSeriesDataset buildDataset(String[] titles,
                                                List<double[]> xValues, List<double[]> yValues) {
        dataset = new XYMultipleSeriesDataset();
        int scale = 0;
        int length = titles.length;
        xyseries = new XYSeries[length];
        for (int i = 0; i < length; i++) {
            xyseries[i] = new XYSeries(titles[i], scale);
            double[] xV = xValues.get(i);
            double[] yV = yValues.get(i);
            if (xV.length != yV.length) {
                Log.i("my", "buildDataset  横纵坐标个数不等");
                System.exit(1);
            }
            int seriesLength = xV.length;
            for (int k = 0; k < seriesLength; k++) {
                xyseries[i].add(xV[k], yV[k]);
            }
            dataset.addSeries(xyseries[i]);
        }
        return dataset;
    }

    /**
     * 柱状图坐标点
     *
     * @param titles
     * @param values
     * @return
     */
    @Override
    protected XYMultipleSeriesDataset buildBarDataset(String[] titles,
                                                      List<double[]> values) {
        dataset = new XYMultipleSeriesDataset();
        int length = titles.length;
        xyseries = new XYSeries[length];
        isShow = new boolean[length];
        for (int i = 0; i < length; i++) {
            CategorySeries series = new CategorySeries(titles[i]);
            double[] v = values.get(i);
            int seriesLength = v.length;
            for (int k = 0; k < seriesLength; k++) {
                series.add(v[k]);
            }
            xyseries[i] = series.toXYSeries();
            dataset.addSeries(xyseries[i]);
            isShow[i] = true;
        }
        return dataset;
    }

    @Override
    protected XYMultipleSeriesRenderer buildRenderer(int[] colors,
                                                     PointStyle[] styles) {
        XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
        setRenderer(renderer, colors, styles);
        return renderer;
    }

    @Override
    protected void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors,
                               PointStyle[] styles) {
        renderer.setAxisTitleTextSize(18);//坐标轴标题字体
        renderer.setChartTitleTextSize(22);//图形标题字体
        renderer.setLabelsTextSize(17);//标签字体
        renderer.setLegendTextSize(17);//每个左下方标题说明
        renderer.setPointSize(5f);
//         renderer.setXLabelsAlign(Align.RIGHT);
//        renderer.setYLabelsAlign(Align.RIGHT);
        renderer.setMargins(new int[]{UIHelper.dip2px(context, 10), UIHelper.dip2px(context, 30), UIHelper.dip2px(context, 10), UIHelper.dip2px(context, 10)});

        renderer.setTextTypeface("sans_serif", Typeface.BOLD);
        renderer.setShowGrid(true);//是否显示网格

        int length = colors.length;
        xySeriesRenderer = new XYSeriesRenderer[length];
        for (int i = 0; i < length; i++) {
            xySeriesRenderer[i] = new XYSeriesRenderer();
            xySeriesRenderer[i].setColor(colors[i]);
            xySeriesRenderer[i].setPointStyle(styles[i]);
            xySeriesRenderer[i].setFillPoints(true);
            if (shapeTypes[i] == SHAPE_AREA_DEFAULT) {
                xySeriesRenderer[i].setFillBelowLine(true);
                xySeriesRenderer[i].setFillBelowLineColor(colors[i]);
            }
            xySeriesRenderer[i].setLineWidth(2.5f);
            xySeriesRenderer[i].setDisplayChartValues(true);//是否显示图形中值字体
            xySeriesRenderer[i].setChartValuesFormat(NumberFormat.getNumberInstance());//设置图形中点的纵坐标取值格式
            xySeriesRenderer[i].setChartValuesTextSize(18f);//设置图形中值字体
//			xySeriesRenderer[i].setDisplayChartValuesDistance(200);//设置图形数值间隔，对于柱状图不起作用
            renderer.addSeriesRenderer(xySeriesRenderer[i]);
        }
    }

    @Override
    public Intent execute(Context context) {
        // TODO Auto-generated method stub
        return null;
    }

    public boolean[] getIsShow() {
        return isShow;
    }

    public void setIsShow(boolean[] isShow) {
        this.isShow = isShow;
    }

}
